package com.heima.comment.service.impl;

import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.CommentService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private UserFeign userFeign;

    @Autowired
    private GreeTextScan greeTextScan;

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存评论
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        if (dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent() == null || dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "评论数不能大于140个数字");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = userFeign.findById(user.getId());
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        /*try {
            Map map = greeTextScan.greeTextScan(dto.getContent());
            if (!map.get("suggestion").equals("pass")){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章中有敏感词汇");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }*/
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setCreatedTime(new Date());
        apComment.setImage(apUser.getImage());
        apComment.setContent(dto.getContent());
        apComment.setEntryId(dto.getArticleId());
        apComment.setFlag((short)0);
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setType((short)0);
        mongoTemplate.insert(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //点赞和取消点赞
    @Override
    public ResponseResult likes(CommentLikeDto dto) {
        if (dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID , "请先登录");
        }
        //查出当前需要操作的评论
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment != null && dto.getOperation() == 0){
            apComment.setLikes(apComment.getLikes()+1);
            mongoTemplate.save(apComment);

            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(apUser.getId());
            apCommentLike.setCommentId(apComment.getId());
            // apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);
        }else if (apComment != null && dto.getOperation() == 1){
            apComment.setLikes(apComment.getLikes() <= 0 ? 0 : apComment.getLikes()-1);
            mongoTemplate.save(apComment);

            Query query = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId").is(apComment.getId()));
            mongoTemplate.remove(query , ApCommentLike.class);
        }
        Map<String , Object> map = new HashMap<>();
        map.put("likes" , apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        if (dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize() == null || dto.getSize() == 0){
            dto.setSize(20);
        }

        //按照文章id过滤，设置分页和排序
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("likes").lt(dto.getMinLikes()));
        query.limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC,"likes"));
        List<ApComment> apCommentLikes = mongoTemplate.find(query, ApComment.class);

        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            return ResponseResult.okResult(apCommentLikes);
        }

        //查出所有的评论id
        List<String> idList = apCommentLikes.stream().map(x -> x.getId()).collect(Collectors.toList());

        Query query1 = Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").in(idList));
        List<ApCommentLike> apCommentLikes1 = mongoTemplate.find(query1, ApCommentLike.class);

        List<ApCommentVo> list = new ArrayList<>();
        if (apCommentLikes1 != null){
            apCommentLikes.stream().forEach(x -> {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(x , apCommentVo);
                for (ApCommentLike apCommentLike : apCommentLikes1) {
                    if (x.getId().equals(apCommentLike.getCommentId())){
                        apCommentVo.setOperation((short)0);
                        break;
                    }
                }
                list.add(apCommentVo);
            });
        }

        return ResponseResult.okResult(list);
    }
}
